package routers

import (
	"encoding/json"
	"net/http"
	"strconv"

	"shqsoft.cn/pasnj/base"
	"shqsoft.cn/pasnj/popedom"

	"strings"

	"github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
)

// GetMenuTree 获取权限树
func GetMenuTree(c echo.Context) error {
	permIDStr := c.FormValue("permID")
	if permIDStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "permID不能为空！")
	}
	permID, err := strconv.Atoi(permIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "permID必须为整数！")
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	pTypes, err := popedom.GetUserPermissionTypes(claims.UserID, permID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	var uid *int
	if !base.IsInSlice(pTypes, "4") && base.IsInSlice(pTypes, "O") {
		uid = &claims.UserID
	}
	treeNodes, err := popedom.GetPermissionTree(uid)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, treeNodes)
}

// GetMenuUserTree 获取用户树
func GetMenuUserTree(c echo.Context) error {
	permIDStr := c.FormValue("permID")
	if permIDStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "permID不能为空！")
	}
	permID, err := strconv.Atoi(permIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "permID必须为整数！")
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	pTypes, err := popedom.GetUserPermissionTypes(claims.UserID, permID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	var pOrgID int
	if !base.IsInSlice(pTypes, "4") && base.IsInSlice(pTypes, "O") {
		pOrgID = claims.ParentOrgID
	}
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	treeNodes, err := popedom.GetOrganTree(pOrgID)
	return c.JSON(http.StatusOK, treeNodes)
}

// GetRolePermsKeys 根据角色ID获取选中权限key
func GetRolePermsKeys(c echo.Context) error {
	rID := c.Param("RoleID")
	if rID == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "角色ID不能为空！")
	}
	rIDInt, err := strconv.Atoi(rID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
	}
	checkedkeys, err := popedom.GetCheckedRolePerms(rIDInt)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, checkedkeys)
}

// GetRoleUsersKeys 根据角色ID获取用户
func GetRoleUsersKeys(c echo.Context) error {
	rID := c.Param("RoleID")
	if rID == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "角色ID不能为空！")
	}
	rIDInt, err := strconv.Atoi(rID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
	}
	checkedkeys, err := popedom.GetCheckedRoleUsers(rIDInt)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, checkedkeys)
}

// SaveRolePerms 保存角色权限
func SaveRolePerms(c echo.Context) error {
	rID := c.Param("RoleID")
	if rID == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "角色ID不能为空！")
	}
	rIDInt, err := strconv.Atoi(rID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
	}
	var rolePerms []string
	jsonStr := c.FormValue("RolePerms")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "rolePerms不能为空！")
	}
	err = json.Unmarshal([]byte(jsonStr), &rolePerms)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	// if l := len(rolePerms); l == 0 {
	// 	return echo.NewHTTPError(http.StatusBadRequest, "rolePerms不能为空数组！")
	// }
	var roleUsers []string
	jsonStr = c.FormValue("RoleUsers")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "roleUsers不能为空！")
	}
	err = json.Unmarshal([]byte(jsonStr), &roleUsers)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	// if l := len(roleUsers); l == 0 {
	// 	return echo.NewHTTPError(http.StatusBadRequest, "roleUsers不能为空数组！")
	// }
	premMap := make(map[int]string)
	for _, rp := range rolePerms {
		pType := strings.Split(rp, ":")
		if len(pType) < 2 {
			continue
		}
		pID, err := strconv.Atoi(pType[0])
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
		}
		pts, ok := premMap[pID]
		if !ok {
			pts = ""
		} else {
			pts = pts + ","
		}
		pts = pts + pType[1]
		premMap[pID] = pts
	}
	uIDs := make([]int, 0, len(roleUsers))
	for _, ru := range roleUsers {
		rUIDS := strings.Split(ru, ":")
		if len(rUIDS) < 2 {
			continue
		}
		uID, err := strconv.Atoi(rUIDS[1])
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
		}
		uIDs = append(uIDs, uID)
	}
	err = popedom.GrantPermissionsAndUsersToRole(rIDInt, premMap, uIDs...)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "保存失败")
	}
	return c.JSON(http.StatusOK, "OK")
}

// GetRolePermsKeys 根据用户ID获取选中权限key
func GetUserPermsKeys(c echo.Context) error {
	uID := c.Param("UserID")
	if uID == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "用户ID不能为空！")
	}
	uIDInt, err := strconv.Atoi(uID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
	}
	checkedkeys, err := popedom.GetCheckedUserPerms(uIDInt)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, checkedkeys)
}

// GetRoleUsersKeys 根据用户ID获取角色
func GetUserRolesKeys(c echo.Context) error {
	uID := c.Param("UserID")
	if uID == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "用户ID不能为空！")
	}
	uIDInt, err := strconv.Atoi(uID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
	}
	checkedkeys, err := popedom.GetCheckedUserRoles(uIDInt)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, checkedkeys)
}

// SaveRolePerms 保存用户权限
func SaveUserPerms(c echo.Context) error {
	uID := c.Param("UserID")
	if uID == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "用户ID不能为空！")
	}
	uIDInt, err := strconv.Atoi(uID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
	}
	var userPerms []string
	jsonStr := c.FormValue("UserPerms")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "UserPerms不能为空！")
	}
	err = json.Unmarshal([]byte(jsonStr), &userPerms)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	var userRoles []string
	jsonStr = c.FormValue("UserRoles")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "userRoles不能为空！")
	}
	err = json.Unmarshal([]byte(jsonStr), &userRoles)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	premMap := make(map[int]string)
	for _, up := range userPerms {
		pType := strings.Split(up, ":")
		if len(pType) < 2 {
			continue
		}
		pID, err := strconv.Atoi(pType[0])
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
		}
		pts, ok := premMap[pID]
		if !ok {
			pts = ""
		} else {
			pts = pts + ","
		}
		pts = pts + pType[1]
		premMap[pID] = pts
	}
	rIDs := make([]int, 0, len(userRoles))
	for _, ur := range userRoles {
		rID, err := strconv.Atoi(ur)
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
		}
		rIDs = append(rIDs, rID)
	}

	err = popedom.GrantPermissionsAndRolesToUser(uIDInt, premMap, rIDs...)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "保存失败")
	}
	return c.JSON(http.StatusOK, "OK")
}

// UserPermissionTypesRouter 获取用户指定权限的所有权限ID
func UserPermissionTypesRouter(c echo.Context) error {
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	permIDStr := c.Param("PermID")
	if permIDStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "权限ID不能为空！")
	}
	permID, err := strconv.Atoi(permIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
	}
	pTypes, err := popedom.GetUserPermissionTypes(claims.UserID, permID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err)
	}
	return c.JSON(http.StatusOK, pTypes)
}
